<template>
  <div class="bg-gray-50 min-h-screen p-4">
    <div class="container mx-auto">
      <!-- 页面标题 -->
      <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
        <h1 class="text-2xl font-bold text-gray-800">食堂平均配餐时间分析</h1>
        <p class="text-gray-600 mt-2">监控配餐效率，优化流程，提升服务质量</p>
      </div>
      
      <!-- 筛选条件 -->
      <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
        <el-form :inline="true" class="space-x-4">
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
          
          <el-form-item label="配餐窗口">
            <el-select v-model="windowId" placeholder="请选择配餐窗口">
              <el-option label="全部窗口" value="all"></el-option>
              <el-option label="窗口1" value="1"></el-option>
              <el-option label="窗口2" value="2"></el-option>
              <el-option label="窗口3" value="3"></el-option>
              <el-option label="窗口4" value="4"></el-option>
              <el-option label="窗口5" value="5"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="时间段">
            <el-select v-model="timePeriod" placeholder="请选择时间段">
              <el-option label="早餐" value="breakfast"></el-option>
              <el-option label="午餐" value="lunch"></el-option>
              <el-option label="晚餐" value="dinner"></el-option>
              <el-option label="全天" value="all"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="fetchData">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <el-card class="bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-xl shadow-lg">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm opacity-90">平均配餐时间</p>
              <h3 class="text-3xl font-bold mt-1">{{ avgMealPreparationTime }} 秒</h3>
              <p class="text-xs mt-2"><i class="fa-solid fa-arrow-down text-green-300 mr-1"></i> 较上周缩短 8.2%</p>
            </div>
            <div class="w-12 h-12 bg-white/20 rounded-full flex items-center justify-center">
              <i class="fa-solid fa-clock text-xl"></i>
            </div>
          </div>
        </el-card>
        
        <el-card class="bg-gradient-to-r from-green-500 to-green-600 text-white rounded-xl shadow-lg">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm opacity-90">配餐效率评分</p>
              <h3 class="text-3xl font-bold mt-1">{{ preparationEfficiencyScore }}</h3>
              <p class="text-xs mt-2"><i class="fa-solid fa-arrow-up text-green-300 mr-1"></i> 较上周提升 5.7%</p>
            </div>
            <div class="w-12 h-12 bg-white/20 rounded-full flex items-center justify-center">
              <i class="fa-solid fa-star text-xl"></i>
            </div>
          </div>
        </el-card>
        
        <el-card class="bg-gradient-to-r from-orange-500 to-orange-600 text-white rounded-xl shadow-lg">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm opacity-90">最高配餐量窗口</p>
              <h3 class="text-3xl font-bold mt-1">窗口{{ busiestWindow }}</h3>
              <p class="text-xs mt-2"><i class="fa-solid fa-bolt text-yellow-300 mr-1"></i> 今日配餐 {{ busiestWindowCount }} 份</p>
            </div>
            <div class="w-12 h-12 bg-white/20 rounded-full flex items-center justify-center">
              <i class="fa-solid fa-cutlery text-xl"></i>
            </div>
          </div>
        </el-card>
        
        <el-card class="bg-gradient-to-r from-red-500 to-red-600 text-white rounded-xl shadow-lg">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm opacity-90">配餐超时率</p>
              <h3 class="text-3xl font-bold mt-1">{{ timeoutRate }}%</h3>
              <p class="text-xs mt-2"><i class="fa-solid fa-arrow-down text-green-300 mr-1"></i> 较上周下降 3.1%</p>
            </div>
            <div class="w-12 h-12 bg-white/20 rounded-full flex items-center justify-center">
              <i class="fa-solid fa-exclamation-triangle text-xl"></i>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 图表区域 -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <!-- 平均配餐时间趋势图 -->
        <el-card class="rounded-xl shadow-lg">
          <div class="flex justify-between items-center mb-4">
            <h3 class="font-bold text-gray-800">平均配餐时间趋势</h3>
            <el-select v-model="timeTrendType" size="small" @change="updateTimeTrendChart">
              <el-option label="按天" value="day"></el-option>
              <el-option label="按周" value="week"></el-option>
              <el-option label="按月" value="month"></el-option>
            </el-select>
          </div>
          <div ref="timeTrendChartRef" class="h-80"></div>
        </el-card>
        
        <!-- 各窗口配餐效率对比 -->
        <el-card class="rounded-xl shadow-lg">
          <div class="flex justify-between items-center mb-4">
            <h3 class="font-bold text-gray-800">各窗口配餐效率对比</h3>
            <el-radio-group v-model="windowChartType" size="small">
              <el-radio-button label="time">配餐时间</el-radio-button>
              <el-radio-button label="count">配餐数量</el-radio-button>
            </el-radio-group>
          </div>
          <div ref="windowChartRef" class="h-80"></div>
        </el-card>
      </div>
      
      <!-- 详细数据表格 -->
      <el-card class="rounded-xl shadow-lg">
        <div class="flex justify-between items-center mb-4">
          <h3 class="font-bold text-gray-800">配餐时间详细数据</h3>
          <div class="flex space-x-2">
            <el-button size="small" type="primary" @click="exportData">导出数据</el-button>
            <el-button size="small" @click="refreshData">刷新</el-button>
          </div>
        </div>
        
        <el-table :data="preparationTimeData" stripe style="width: 100%">
          <el-table-column prop="date" label="日期"></el-table-column>
          <el-table-column prop="window" label="配餐窗口"></el-table-column>
          <el-table-column prop="timePeriod" label="时间段"></el-table-column>
          <el-table-column prop="avgTime" label="平均配餐时间(秒)"></el-table-column>
          <el-table-column prop="mealCount" label="配餐数量"></el-table-column>
          <el-table-column prop="timeoutCount" label="超时次数"></el-table-column>
          <!--<el-table-column prop="efficiency" label="效率评分" :formatter="efficiencyFormatter"></el-table-column>-->
        </el-table>
        
        <!-- 分页 -->
        <div class="flex justify-between items-center mt-4">
          <div class="text-sm text-gray-500">
            共 {{ total }} 条数据
          </div>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

// 筛选条件
const dateRange = ref(null)
const windowId = ref('all')
const timePeriod = ref('all')

// 图表类型
const timeTrendType = ref('day')
const windowChartType = ref('time')

// 统计数据
const avgMealPreparationTime = ref(58.2)
const preparationEfficiencyScore = ref(92)
const busiestWindow = ref(3)
const busiestWindowCount = ref(328)
const timeoutRate = ref(4.3)

// 表格数据
const preparationTimeData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 图表引用
const timeTrendChartRef = ref(null)
const windowChartRef = ref(null)

// 图表实例
let timeTrendChart = null
let windowChart = null

// 模拟数据 - 平均配餐时间趋势
const getTimeTrendData = (type) => {
  let xAxisData = []
  let seriesData = []
  
  if (type === 'day') {
    xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    seriesData = [65.2, 62.8, 59.7, 58.3, 57.1, 56.5, 55.9]
  } else if (type === 'week') {
    xAxisData = ['第1周', '第2周', '第3周', '第4周', '第5周', '第6周', '第7周', '第8周']
    seriesData = [72.4, 69.8, 66.5, 63.2, 60.7, 58.3, 56.9, 55.2]
  } else {
    xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    seriesData = [85.6, 82.3, 78.9, 74.5, 70.3, 66.8, 63.5, 60.2, 57.8, 55.6, 53.2, 51.8]
  }
  
  return {
    xAxisData,
    seriesData
  }
}

// 模拟数据 - 各窗口配餐效率对比
const getWindowEfficiencyData = (type) => {
  const windowNames = ['窗口1', '窗口2', '窗口3', '窗口4', '窗口5']
  
  if (type === 'time') {
    return {
      xAxisData: windowNames,
      seriesData: [52.3, 60.8, 58.2, 64.5, 56.7],
      yAxisName: '平均配餐时间(秒)',
      color: '#409EFF',
      isLowerBetter: true
    }
  } else {
    return {
      xAxisData: windowNames,
      seriesData: [285, 310, 328, 276, 292],
      yAxisName: '配餐数量',
      color: '#67C23A',
      isLowerBetter: false
    }
  }
}

// 模拟数据 - 配餐时间详细表格
const getPreparationTimeTableData = (page, size) => {
  const start = (page - 1) * size
  const end = page * size
  
  const data = []
  const date = new Date()
  
  for (let i = start; i < end && i < 50; i++) {
    const d = new Date(date)
    d.setDate(date.getDate() - i)
    
    const dayOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][d.getDay()]
    const timePeriods = ['早餐', '午餐', '晚餐']
    const timePeriod = timePeriods[Math.floor(Math.random() * 3)]
    
    const windowNum = Math.floor(Math.random() * 5) + 1
    const avgTime = Math.floor(Math.random() * 20) + 50
    const mealCount = Math.floor(Math.random() * 100) + 200
    const timeoutCount = Math.floor(Math.random() * 10)
    
    const efficiency = Math.floor(100 - (avgTime - 50) * 1.5)
    const finalEfficiency = Math.max(50, Math.min(100, efficiency))
    
    data.push({
      id: i + 1,
      date: `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} (${dayOfWeek})`,
      window: `窗口${windowNum}`,
      timePeriod,
      avgTime,
      mealCount,
      timeoutCount,
      efficiency: finalEfficiency
    })
  }
  
  return data
}

// 初始化时间趋势图表
const initTimeTrendChart = () => {
  const { xAxisData, seriesData } = getTimeTrendData(timeTrendType.value)
  
  timeTrendChart = echarts.init(timeTrendChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisPointer: {
        type: 'shadow'
      }
    },
    yAxis: {
      type: 'value',
      name: '秒',
      min: 0,
      max: 100,
      interval: 20
    },
    series: [
      {
        name: '平均配餐时间',
        type: 'line',
        data: seriesData,
        color: '#409EFF',
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        markLine: {
          data: [
            { type: 'average', name: '平均值' }
          ]
        }
      }
    ]
  }
  
  timeTrendChart.setOption(option)
}

// 初始化窗口对比图表
const initWindowChart = () => {
  const { xAxisData, seriesData, yAxisName, color, isLowerBetter } = getWindowEfficiencyData(windowChartType.value)
  
  windowChart = echarts.init(windowChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisPointer: {
        type: 'shadow'
      }
    },
    yAxis: {
      type: 'value',
      name: yAxisName,
      min: 0,
      max: isLowerBetter ? 100 : 400,
      interval: isLowerBetter ? 20 : 80
    },
    series: [
      {
        name: windowChartType.value === 'time' ? '配餐时间' : '配餐数量',
        type: 'bar',
        data: seriesData,
        color: color
      }
    ]
  }
  
  windowChart.setOption(option)
}

// 更新时间趋势图表
const updateTimeTrendChart = () => {
  const { xAxisData, seriesData } = getTimeTrendData(timeTrendType.value)
  
  timeTrendChart.setOption({
    xAxis: {
      data: xAxisData
    },
    series: [
      {
        data: seriesData
      }
    ]
  })
}

// 更新窗口对比图表
const updateWindowChart = () => {
  const { xAxisData, seriesData, yAxisName, color, isLowerBetter } = getWindowEfficiencyData(windowChartType.value)
  
  windowChart.setOption({
    xAxis: {
      data: xAxisData
    },
    yAxis: {
      name: yAxisName,
      min: 0,
      max: isLowerBetter ? 100 : 400,
      interval: isLowerBetter ? 20 : 80
    },
    series: [
      {
        name: windowChartType.value === 'time' ? '配餐时间' : '配餐数量',
        data: seriesData,
        color: color
      }
    ]
  })
}

// 刷新数据
const refreshData = () => {
  // 显示加载状态
  timeTrendChart.showLoading()
  windowChart.showLoading()
  
  // 模拟数据加载
  setTimeout(() => {
    // 更新统计数据
    avgMealPreparationTime.value = (Math.random() * 10 + 50).toFixed(1)
    preparationEfficiencyScore.value = Math.floor(Math.random() * 8 + 85)
    busiestWindow.value = Math.floor(Math.random() * 5) + 1
    busiestWindowCount.value = Math.floor(Math.random() * 100) + 250
    timeoutRate.value = (Math.random() * 5 + 3).toFixed(1)
    
    // 更新表格数据
    preparationTimeData.value = getPreparationTimeTableData(currentPage.value, pageSize.value)
    total.value = 50
    
    // 更新图表
    updateTimeTrendChart()
    updateWindowChart()
    
    // 隐藏加载状态
    timeTrendChart.hideLoading()
    windowChart.hideLoading()
    
    // 显示成功提示
    ElMessage.success('数据刷新成功')
  }, 800)
}

// 重置筛选条件
const resetFilter = () => {
  dateRange.value = null
  windowId.value = 'all'
  timePeriod.value = 'all'
}

// 获取数据
const fetchData = () => {
  // 显示加载状态
  timeTrendChart.showLoading()
  windowChart.showLoading()
  
  // 模拟数据加载
  setTimeout(() => {
    // 更新表格数据
    preparationTimeData.value = getPreparationTimeTableData(currentPage.value, pageSize.value)
    total.value = 50
    
    // 更新图表
    updateTimeTrendChart()
    updateWindowChart()
    
    // 隐藏加载状态
    timeTrendChart.hideLoading()
    windowChart.hideLoading()
    
    // 显示成功提示
    ElMessage.success('数据加载成功')
  }, 800)
}

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  fetchData()
}

// 处理当前页变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchData()
}

// 导出数据
const exportData = () => {
  ElMessage.info('数据导出功能开发中...')
}

// 效率格式化
const efficiencyFormatter = (row) => {
  const efficiency = row.efficiency
  let color = ''
  
  if (efficiency >= 90) color = 'text-green-500'
  else if (efficiency >= 75) color = 'text-yellow-500'
  else color = 'text-red-500'
  
  return `<span class="${color}">${efficiency}分</span>`
}

// 页面加载时初始化
onMounted(() => {
  nextTick(() => {
    // 初始化图表
    initTimeTrendChart()
    initWindowChart()
    
    // 加载数据
    fetchData()
    
    // 监听窗口大小变化，调整图表
    window.addEventListener('resize', () => {
      timeTrendChart.resize()
      windowChart.resize()
    })
    
    // 监听图表类型变化
    watch(windowChartType, () => {
      updateWindowChart()
    })
  })
})
</script>

<style scoped>

</style>